var toolBarElements = new Array();
var toolBarIconSpaceX = 100;
var toolBarIconSpaceY = 10;

var containerMargin = 30;
var columnMargin = 20;

var columnLeft = 300;
var columnMiddle = 350;
var columnRight = 300;

var accordionAnimation = "slide";

var searchWayPointWM = "Search near by";

var activeToggleButton = null;

//var toolBarContainerId = "#toolBar";

//var toolBarIconClass = ".toolBarIcon";
//var mapControlsClass = ".gmnoprint";

var mapCenter = new GLatLng(33.956461,-118.396225);
var mapZoom = 8;

var map;
var gdir;
var geocoder = null;
var addressMarker;
var wayPoints = new Array();

jQuery.event.add(window, "load", refreshLayout);
jQuery.event.add(window, "resize", refreshLayout);

$(function() {
	$("#accordionLeft").accordion({
		fillSpace: true,
		animated: 'slide',
		changestart: function(event, ui) { 
			$("#accordionRight").accordion( 'activate' , $("#accordionLeft").find("h3").index(ui.newHeader[0]));
			if(activeToggleButton != null) {
				$(activeToggleButton).trigger("click", ["quick"]);
			}
		}
	});

	$("#accordionRight").accordion({
		fillSpace: true,
		animated: 'slide',
		changestart: function(event, ui) {
			$("#accordionLeft").accordion( 'activate' , $("#accordionRight").find("h3").index(ui.newHeader[0]));
			if(activeToggleButton != null) {
				$(activeToggleButton).trigger("click", ["quick"]);
			}
		}
	});

	$(".sortable").sortable({
		placeholder: 'ui-state-highlight',
		scroll: false,
	});

	$("#wayPointsLeft .wayPointInsert").click(function() {
		var wayPointDiv = $(this).parent().parent();
		var wayPointDivNew = $("#wayPointsRight").find(cls(wayPointDiv.attr("class")));

		wayPointDiv.parent().hide("slide", { direction: "right" });
		wayPointDivNew.parent().show("slide", { direction: "left" });

		wayPointDivNew.find('.wayPointRemove').click(removeFun = function() {
			wayPointDiv.parent().show("slide", { direction: "left" });
			wayPointDivNew.parent().hide("slide", { direction: "right" });
			$(this).unbind("click");
		});
	});

	$('#wayPointsRangeSelector').slider({
		range: "min",
		value: 5,
		min: 0,
		max: 50,
		step: 0.5,
		slide: function(event, ui) {
			$("#wayPointsRangeValue").val(ui.value.toFixed(1) + "km");
		}
	});

	$('.iWayPointsRangeSelector').slider({
		range: "min",
		value: 5,
		min: 0,
		max: 50,
		step: 0.5,
		slide: function(event, ui) {
			$(".iWayPointsRangeValue").val(ui.value.toFixed(1) + "km");
		}
	});

	$('.locationMarker').draggable({ 
		helper : 'clone', 
		containment : 'document', 
		scroll : false, 
		zIndex : 2700,
		stop : markerDragend,
		start : function(event, ui) {}
	});
	
	$('#findRoute').click(function() {
		var dir = "from: " + wayPoints[0].toUrlValue();
		for(i = 1; i < wayPoints.length - 1; i ++) {
			dir += " to:" + wayPoints[i].toUrlValue();
		}
		dir += " to:" + wayPoints[wayPoints.length -1].toUrlValue();
		gdir.load(dir, { "locale": "en_US" });
	});

	$(".toggleButton").toggle(
		function(event) {
			if(activeToggleButton != null) {
				$(activeToggleButton).trigger("click", ["quick"]);
			}
			activeToggleButton = this;
			$(activeToggleButton).parent().parent().parent().find(".toolsPanel").show("slide", { direction: "up" });
		},
		function(event, mode) {
			if(mode == "quick") {
				$(activeToggleButton).parent().parent().parent().find(".toolsPanel").hide();
			} else {
				$(activeToggleButton).parent().parent().parent().find(".toolsPanel").hide("slide", { direction: "up" });
			}
			activeToggleButton = null;
		}
	);

	$('#wayPointsRangeValue').val($('#wayPointsRangeSelector').slider("value").toFixed(1) + "km");
	$('.overflowVisible').css("overflow", "visible");
	$('#searchBoxWayPoint').Watermark(searchWayPointWM);
	//$("#placeSearchBox").Watermark("Search", "#369");
	$(".sortable").disableSelection();
	$("#columnRight .iconBar").hide();

});

function markerDragend(event, ui) {
	var dragger = $(".locationMarker.ui-draggable-dragging").position();
	var wpId = $(this).parent().attr("id").substring(2);
	$("#mapContainer").mousemove(createMarker = function(e) {

		$(this).unbind('mousemove', createMarker);

		//var fPos = $(iconId).position();
		var mPos = $("#mapContainer").position();
		//var iconW = $(iconId).width();
		//var iconH = $(iconId).height();	
		var mapX = mPos.left;
		var mapY = mPos.top;

		//var mPoint = new GPoint(e.pageX - mapX + Math.floor((iconW - 1)/2), e.pageY + iconH - mapY);
		var mPoint = new GPoint(e.pageX - mapX, e.pageY - mapY);

		if(map.getBounds().containsLatLng(map.fromContainerPixelToLatLng(mPoint))) {
			var mLatLng = map.fromContainerPixelToLatLng(mPoint);
			var marker = new GMarker(mLatLng, {draggable:true, autoPan:false});
			map.addOverlay(marker);
			wayPoints[wpId] = mLatLng;
		}
	});
}

function UseData(){
   $.Watermark.HideAll();
   //Do Stuff
   $.Watermark.ShowAll();
}

function id(divName) {
	return "#" + divName;
}

function cls(className) {
	return "." + className;
}

function pixel(value) {
	return value + "px";
}

function refreshLayout() {

	var minWidth = containerMargin + columnLeft + columnMargin + columnMiddle + columnMargin + columnRight + containerMargin;

    var height = $(window).height();
	var width = $(window).width();
    
	$("#mainContainer").css({'margin-left' : pixel(containerMargin), 'margin-right' : pixel(containerMargin)});
	$("#columnLeft").css({'width' : pixel(columnLeft)});
	$("#columnRight").css({'width' : pixel(columnRight)});
	$("#columnMiddle").css({'margin-left' : pixel(columnMargin), 'margin-right' : pixel(columnMargin)});

	if(width > minWidth) {
		$("#mainContainer").css({'width' : pixel(width - 2*containerMargin)});
		$("#columnMiddle").css({'width' : pixel(width - (2*(containerMargin + columnMargin) + columnLeft + columnRight))});
	} else {
		$("#mainContainer").css({'width' : pixel(minWidth - 2*containerMargin)});
		$("#columnMiddle").css({'width' : pixel(minWidth - (2*(containerMargin + columnMargin) + columnLeft + columnRight))});
        $("#body").css({'width' : pixel(minWidth)});
	}
}

function initialize(center, zoom) {
	
	if (GBrowserIsCompatible()) {
		var mapOptions = {
			googleBarOptions : {
			  style : "new"
			}
		};
		map = new GMap2(document.getElementById("mapContainer"), mapOptions);
		map.setCenter(center, zoom);
		map.setUIToDefault();
		map.enableGoogleBar();

		gdir = new GDirections(map, document.getElementById("journey-routes"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);

		//initializeToolBar();
	}
}

/*function initializeToolBar() {
	var currentX = 0;
	var currentY = 0;

	var currentCol = 0;
	var currentRow = 0;

	var iconCols = parseInt($(toolBarContainerId).width() / toolBarIconSpaceX - 1);
	var iconRows = parseInt($(toolBarContainerId).height() / toolBarIconSpaceY - 1);
	var row = new Array(iconCols);

	$(toolBarIconClass).each(function(i) {
		var iconId = id(this.id);			
		if(currentCol < iconCols) {			
			row[currentCol] = new GDraggableObject(this, {draggingCursor: "pointer", draggableCustor: "pointer"});
			row[currentCol].moveBy(new GSize(currentX, currentY));
			currentX += toolBarIconSpaceX;
		} else {
			toolBarElements[currentRow] = row;
			row = new Array(iconCols);
			currentRow++;
			currentCol = 0;
			currentX = 0;
			currentY += toolBarIconSpaceY;
			row[currentCol] = new GDraggableObject(this, {draggingCursor: "pointer", draggableCustor: "pointer"});
			row[currentCol].moveBy(new GSize(currentX, currentY));
		}

		var iconDragStart = GEvent.addListener(row[currentCol], "dragstart", function() {
			var iPos = $(iconId).position();
			$(iconId).css("z-index", 1);
			$(mapControlsClass).css("z-index", 2);			
			$(draggerId).css({'left' : pixel(iPos.left), 'top' : pixel(iPos.top), 'position' : 'absolute', 'display' : 'block'});
		}); 

		var iconDragEnd = GEvent.addListener(row[currentCol], "dragend", function() {

			var fPos = $(iconId).position();
			var mPos = $("#mapContainer").position();
			var iconW = $(iconId).width();
			var iconH = $(iconId).height();	
			var mapX = mPos.left;
			var mapY = mPos.top;
			
			var mPoint = new GPoint(fPos.left - mapX + Math.floor((iconW - 1)/2), fPos.top + iconH - mapY);

			if(map.getBounds().containsLatLng(map.fromContainerPixelToLatLng(mPoint))) {
				var mLatLng = map.fromContainerPixelToLatLng(mPoint);
				var marker = new GMarker(mLatLng, {draggable:true, autoPan:false});
				$("#headerRight").text("Hello");
				map.addOverlay(marker);
			}

			$(iconId).css("z-index", 0);
			$(mapControlsClass).css("z-index", 0); 
			var position = $(draggerId).position();
			this.moveTo(new GPoint(position.left, position.top));
			$(draggerId).css({'display' : 'none'});
		});

		currentCol++;
	});	
}
*/
function handleErrors(){
   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
   
   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
     
   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
    
   else alert("An unknown error occurred.");
   
}

function onGDirectionsLoad(){ 
  // Use this function to access information about the latest load()
  // results.

  // e.g.
  // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
  // and yada yada yada..
}
